#!/usr/bin/env python
# coding: utf-8

# 将tRNAscan的结果输出为

import sys
import argparse


parser = argparse.ArgumentParser(
    description='''将tRNAscan的结果转化为gff3
    用法:
    tRNAscan2gff3.py -i tRNA.out -o tRNA.gff3 -p NIG_ONT_tRNA
    由大天才于2021年7月29日创建于浙江农业大学''')

parser.add_argument('-i',
                help='必须给定，输入tRNAscan的结果')


parser.add_argument('-o',
                help='必须给定，输出文件的路径')

parser.add_argument('-p',
                help='前缀，默认为tRNA')


args = parser.parse_args()

if not args.i or not args.o:
    parser.print_help()
    sys.exit()


infile = args.i

outfile  = args.o



if not args.p:
    prefix = 'tRNA'
else:
    prefix = args.p




id_dic=  {}

fita = open(outfile,'w')

fita.write('##gff-version 3.2.1\n')

with open(infile) as fila:
    next(fila);next(fila);next(fila)
    for i in fila:
        l = i.strip()
        k = l.split('\t')
        if len(k)>=5:
            scaf = k[0].strip()

            type_name = k[4]

            if type_name not in id_dic:

                id_dic[type_name] = 1
            else:
                id_dic[type_name] += 1

            name = prefix+'_'+type_name+'_'+str(id_dic[type_name])
            
    
            s = int(k[2].strip())
            e = int(k[3].strip())
            
            if s > e:
                begin = e
                end = s
                d = '-'
            else:
                begin = s
                end = e
                d = '+'
            score = k[8]

        fita.write(scaf+'\t'+'tRNAscan-SE\ttRNA'+'\t'+str(begin)+'\t'+str(end)+'\t.\t'+d+'\t.\tID='+name+'\n')



